package com.zhan.ielts.web.controller;

import com.zhan.frame.core.utils.FileUtils;
import com.zhan.frame.core.web.domain.CustomResult;
import com.zhan.ielts.utils.CustomPropertisUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.activation.MimetypesFileTypeMap;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;

@Controller
@RequestMapping("/download")
public class DownloadController {

    private Logger log = LoggerFactory.getLogger(DownloadController.class);


    @ResponseBody
    @RequestMapping(method = RequestMethod.GET)
    public CustomResult fetchTreasureChest(String filePath, HttpServletResponse response) {
        filePath = CustomPropertisUtils.getProperties("STATISTICS_LOG_PATH");
        String toPath = filePath + File.separator + "log.zip";

        File f = new File(toPath);
        if (f.exists()) {
            f.delete();
        }
        FileUtils.zipFile(filePath, toPath, null, null);
        //设置文件MIME类型
        response.setContentType(new MimetypesFileTypeMap().getContentType(f));
        //设置Content-Disposition
        response.setHeader("Content-Disposition", "attachment;filename=log.zip");
        //读取目标文件，通过response将目标文件写到客户端
        //读取文件
        InputStream in = null;
        OutputStream out = null;
        try {
            in = new FileInputStream(toPath);
            out = response.getOutputStream();
            //写文件
            int b;
            while ((b = in.read()) != -1) {
                out.write(b);
            }
            in.close();
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        f.delete();
        return new CustomResult();
    }

}
